"""
@File    : user.py
@Time    : 2021/5/30 23:07
@Author  : chenhuayan
@Software: PyCharm
"""
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask, jsonify, request, send_from_directory
from common.mysql_operate import db
from common.redis_operate import redis_db
from common.md5_operate import get_md5
import os
import re
import time

app = Flask(__name__)
app.config["JSON_AS_ASCII"] = False  # jsonify返回的中文正常显示


@app.route('/')
def hello_world():
    return 'Hello world!'


@app.route('/users', methods=['GET'])
def get_all_users():
    """获取所有用户信息"""
    sql = 'SELECT * FROM user'
    data = db.select_db(sql)
    print(f'获取所有用户信息 == >> {data}')
    return jsonify({'code': 0, 'data': data, 'msg': '查询成功'})


@app.route('/users/<string:username>', methods=['GET'])
def get_user(username):
    """获取某个用户信息"""
    sql = f'SELECT * FROM user WHERE username = "{username}"'
    data = db.select_db(sql)
    print(f'获取{username}用户信息==>>{data}')
    if data:
        return jsonify({'code': 0, 'data': data, 'msg': '查询成功'})
    return jsonify({'code': '1004', 'msg': '查不到相关用户的信息'})


@app.route('/register', methods=['POST'])
def user_register():
    """注册用户"""
    username = request.json.get('username', '').strip()  # 用户名
    password = request.json.get('password', '').strip()  # 密码
    sex = request.json.get('sex', '0').strip()  # 性别 默认为0（男性）
    telephone = request.json.get('telephone', '').strip()  # 手机号
    address = request.json.get('address', '').strip()  # 地址 默认为空串
    if username and password and telephone:  # 注意if条件中 "" 也是空, 按False处理
        sql1 = f'SELECT username FROM user WHERE username = "{username}"'
        res1 = db.select_db(sql1)
        print("查询到用户名 ==>> {}".format(res1))
        sql2 = f'SELECT telephone FROM user WHERE telephone = "{telephone}"'
        res2 = db.select_db(sql2)
        print("查询到手机号 ==>> {}".format(res2))
        if res1:
            return jsonify({'code': 2002, 'msg': '用户名已存在，注册失败！！！'})
        elif not (sex == '0' or sex == '1'):
            return jsonify({'code': 2003, 'msg': '输入的性别只能是 0(男) 或 1(女)！！！'})
        elif not (len(telephone) == 11 and re.match('^1[3,5,7,8]\d{9}$', telephone)):
            return jsonify({"code": 2004, "msg": "手机号格式不正确！！！"})
        elif res2:
            return jsonify({"code": 2005, "msg": "手机号已被注册！！！"})
        else:
            # 把传入的明文密码通过MD5加密变为密文，然后再进行注册
            password = get_md5(username, password)
            sql3 = f'INSERT INTO user(username, password, role, sex, telephone, address)' \
                   f'VALUES("{username}","{password}","1","{sex}","{telephone}","{address}")'
            res_num = db.execute_db(sql3)
            print(f"新增用户信息SQL ==>> {sql3},影响行数为{res_num}")
            if res_num:
                return jsonify({"code": 0, "msg": "恭喜，注册成功！"})
            else:
                return jsonify({"code": 500, "msg": "注册失败，请联系开发~"})
    else:
        return jsonify({"code": 2001, "msg": "用户名/密码/手机号不能为空，请检查！！！"})


@app.route('/login', methods=['POST'])
def user_login():
    """用户登录"""
    username = request.values.get('username', '').strip()
    password = request.values.get('password', '').strip()
    if username and password:
        sql1 = f'SELECT username FROM user WHERE username ="{username}"'
        res1 = db.select_db(sql1)
        print(f"查询到用户名==>>{username}")
        if not res1:
            return jsonify({'code': 1003, 'msg': '用户名不存在'})
        md5_password = get_md5(username, password)
        sql2 = f'SELECT * FROM user WHERE username ="{username}" and password ="{md5_password}"'
        res2 = db.select_db(sql2)
        if res2:
            # 获取当前时间戳
            timeStamp = int(time.time())
            token = get_md5(username, str(timeStamp))
            # 把token放到redis中存储
            redis_db.handle_redis_token(username, token)
            # 构造一个字典，将 id/username/token/login_time 返回
            login_info = {
                'id': res2[0]['id'],
                'username': username,
                'token': token,
                'login_time': time.strftime('%Y-%m-%d %H:%M:%S')
            }
            return jsonify({'code': 0, 'data': login_info, 'msg': '恭喜，登录成功！'})
        else:
            return jsonify({"code": 1002, "msg": "用户名或密码错误！！！"})
    else:
        return jsonify({"code": 1001, "msg": "用户名或密码不能为空！！！"})


# 加上它 就不报404了
@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'static'),
                               'favicon.ico', mimetype='image/vnd.microsoft.icon')
